<template>
  <div class="attendance-page">
    <!-- 学生选择 -->
    <van-field
        v-model="attendance.studentName"
        placeholder="请选择学生"
        label="学生："
        is-link
        readonly
        @click="showStudentPicker = true"
        class="text"
    >
    </van-field>
    <van-popup v-model:show="showStudentPicker" round position="bottom">
      <van-picker :columns="studentOptions" @confirm="onStudentConfirm" @cancel="showStudentPicker = false" />
    </van-popup>

    <!-- 状态选择 -->
    <van-field
        v-model="attendance.statusName"
        placeholder="请选择状态"
        label="状态："
        is-link
        readonly
        @click="showStatusPicker = true"
        class="text"
    >
    </van-field>
    <van-popup v-model:show="showStatusPicker" round position="bottom">
      <van-picker :columns="statusOptions" @confirm="onStatusConfirm" @cancel="showStatusPicker = false" />
    </van-popup>

    <!-- 日期选择器 -->
    <van-cell class="date-picker-cell">
      <div @click="openCalendar">选择时间
        <img src="../../assets/images/calendar.png" class="calendar-icon" />
        <span v-if="attendance.time">{{ formatTime(attendance.time) }}</span>
      </div>
    </van-cell>
    <van-popup v-model:show="showCalendar" round position="bottom">
      <van-datetime-picker
          v-model="attendance.time"
          type="datetime"
          title="选择完整时间"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="onDateConfirm"
          @cancel="showCalendar = false"
      />
    </van-popup>

    <!-- 文件上传 -->
    <van-field label="文件上传">
      <template #input>
        <van-uploader v-model="attendance.photo" multiple :max-count="1" />
      </template>
    </van-field>

    <!-- 提交按钮 -->
    <van-button
        type="primary"
        class="submit-button"
        @click="submitAttendance"
    >
      提交考勤
    </van-button>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { Toast } from 'vant';
import axios from 'axios';

// 定义考勤信息
const attendance = reactive({
  studentId: '',
  studentName: '',
  status: '',
  statusName: '',
  time: new Date().toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-'),
  photo: []
});

// 学生选项
const studentOptions = ref([]);
const statusOptions = ref([{ text: '未签到', value: 0 }, { text: '已签到', value: 1 }]);

// 控制日历显示隐藏
const showCalendar = ref(false);
const minDate = new Date(2020, 0, 1);
const maxDate = ref(new Date());
const showStudentPicker = ref(false);
const showStatusPicker = ref(false);

// 获取学生选项
const fetchStudentOptions = async () => {
  try {
    const response = await axios.get('/api/student/by-teacher-or-parent');
    studentOptions.value = response.data.data.map(student => ({
      text: student.studentName,
      value: student.studentId
    }));
  } catch (error) {
    console.error('Failed to fetch student options:', error);
  }
};

// 确认选择的学生
const onStudentConfirm = (value) => {
  attendance.studentId = value.value;
  attendance.studentName = value.text;
  showStudentPicker.value = false;
};

// 确认选择的状态
const onStatusConfirm = (value) => {
  attendance.status = value.value;
  attendance.statusName = value.text;
  showStatusPicker.value = false;
};

// 打开日历并设置默认值为当前时间
const openCalendar = () => {
  const now = new Date();
  attendance.time = now.toISOString();
  maxDate.value = now;
  showCalendar.value = true;
};

// 确认选择的日期
const onDateConfirm = (value) => {
  attendance.time = value.toISOString();
  showCalendar.value = false;
};

// 提交考勤信息
const submitAttendance = async () => {
  try {
    console.log('Submitting Attendance Form:', attendance);
    const formData = new FormData();
    formData.append('studentId', attendance.studentId);
    formData.append('status', attendance.status);
    formData.append('time', attendance.time);
    if (attendance.photo.length > 0) {
      formData.append('file', attendance.photo[0].file);
    }
    const response = await axios.post('/api/attendance/add', formData);
    if (response.data.code === 2000) {
      Toast.success('提交成功');
      attendance.studentId = '';
      attendance.studentName = '';
      attendance.status = '';
      attendance.statusName = '';
      attendance.time = new Date().toISOString();
      attendance.photo = [];
    } else {
      Toast.fail(response.data.message);
    }
  } catch (error) {
    Toast.fail('提交失败');
    console.error('Failed to submit attendance:', error);
  }
};

// 格式化时间显示
const formatTime = (time) => {
  return new Date(time).toLocaleString();
};

// 页面加载时获取学生选项
onMounted(() => {
  fetchStudentOptions();
});
</script>

<style scoped>
:root{
  --van-field-label-width: 100%;
}

.attendance-page {
  padding: 20px;
  margin: 15px;
  height: 100%;
}

.text {
  margin: 5px;
  background-color: #ffffff;
  padding: 10px;
  box-sizing: border-box;
  border-radius: 10px;
  border: 1px solid #1e1f22;
  width: 100%;
}

.date-picker-cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 40px;
  margin: 5px;
  background-color: #ffffff;
  padding: 10px;
  box-sizing: border-box;
  border-radius: 10px;
  border: 1px solid #1e1f22;
}

.calendar-icon {
  width: 20px;
  margin-right: 15px;
}

.submit-button {
  margin-left: 50px;
  background-color: rgba(101, 242, 13, 0.622);
  border-radius: 10px;
  padding: 10px;
  box-sizing: border-box;
  width: 200px;
}
</style>
